package com.monster.servlet.user;

import com.monster.service.UserService;
import com.monster.service.UserServiceImpl;
import com.monster.util.UserMessageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/code_reg")
public class CodeRegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phoneNumber = request.getParameter("phone");
        UserService us = new UserServiceImpl();
        String message = "该手机号码已被注册";
        if (us.isRegistered(phoneNumber) == null) {
            String smsCode = UserMessageUtil.getRandomCode();
            String smsText = "您正在注册本站会员，本次验证码为:"+smsCode+"，有效时间为5分钟，如非本人操作，请忽略此信息。";
            UserMessageUtil.sendMessage(phoneNumber, smsText);
            Map<String, Date> smsCodes = new HashMap<>();
            smsCodes.put(smsCode, new Date());
            request.getSession().setAttribute("smsCode", smsCodes);
            request.getSession().setAttribute("code_phone", phoneNumber);
            message = "send";
            System.out.println(smsText);
        }
        PrintWriter out = response.getWriter();
        out.print(message);
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
